package com.stockz.downloaderx.callback;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.stockz.downloaderx.Download;
import com.stockz.downloaderx.Downloader.Callback;
import com.stockz.downloaderx.util.DownloaderUtil;

@Component
public class FilebasePersistenceCallback
implements Callback{
	private static Logger logger = Logger.getLogger(FilebasePersistenceCallback.class);
	
	public int getOrder() {
		return 800;
	}

	public void execute(Download download) {
		if(download != null && StringUtils.hasText(download.getRawData())
				&& download.getDownloadDate() != null && download.getExchange() != null
				&& StringUtils.hasText(download.getExchange().getCode()) 
				&& download.getEvent() != null && EVENT.DOWNLOAD.equals(download.getEvent())
				&& download.getType() != null && TYPE.SUCCESS.equals(download.getType())){
			try {
				File directory = new File(DownloaderUtil.getDownloadDirectoryPath(download.getDownloadDate(), download.getExchange().getCode()));
				if(!directory.exists()){
					directory.mkdirs();
				}
				File file = new File(DownloaderUtil.getDownloadFilePath(download.getDownloadDate(), download.getExchange().getCode()));
				if(!file.exists()){
					file.createNewFile();
				}
				
				BufferedWriter writer = new BufferedWriter(
						new FileWriter(file));
				writer.write(download.getRawData());
				writer.close();
			} catch (IOException e) {
				logger.error("Error while writing to filebase",e);
				throw new RuntimeException(e);
			}
		}
	}
}